package cn.xdmnb.cloud.blog.plugin.redis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author yukai
 * @since 2023年01月05日 13:59
 */
@Configuration
@EnableConfigurationProperties(value = {RedisProperties.class})
@AutoConfigureBefore(value = {RedisAutoConfiguration.class})
public class RedisAutoConfig {

    @Bean
    public JedisPool redisPoolFactory(RedisProperties redisProperties) {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());
        jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWait());
        if (!StringUtils.hasText(redisProperties.getPassword())) {
            return new JedisPool(
                    jedisPoolConfig,
                    redisProperties.getHost(),
                    redisProperties.getPort(),
                    redisProperties.getTimeout(),
                    redisProperties.getPassword(),
                    redisProperties.getDatabase()
            );
        }else{
            return new JedisPool(
                    jedisPoolConfig,
                    redisProperties.getHost(),
                    redisProperties.getPort(),
                    redisProperties.getTimeout(),
                    null,
                    redisProperties.getDatabase()
            );
        }
    }

    @Bean
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getDeclaringClass().getName());
            Arrays.stream(params).map(Object::toString).forEach(sb::append);
            return sb.toString();
        };
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        RedisSerializer<?> stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);// key序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// value序列化
        redisTemplate.setHashKeySerializer(stringSerializer);// Hash key序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// Hash value序列化
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }


    class JacksonRedisSerializer<T> implements RedisSerializer<T> {

        private Class<T> clazz;

        private ObjectMapper mapper;

        public JacksonRedisSerializer(Class<T> clazz) {
            super();
            this.clazz = clazz;
            this.mapper = new ObjectMapper();
            mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        }

        @Override
        public byte[] serialize(T t) throws SerializationException {
            try {
                return mapper.writeValueAsBytes(t);
            }catch (Exception ex){
                ex.printStackTrace();
                return null;
            }
        }

        @Override
        public T deserialize(byte[] bytes) throws SerializationException {
            if (bytes.length <= 0){
                return null;
            }
            try {
                return mapper.readValue(bytes, clazz);
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
        }
    }

}
